# coding:utf-8

from common.entities import Category, Categories, Product, Products
from common.htmlparser import HtmlParser
from common.utils import cstrtime
import json


class ProductDetailsParser:
    __parser = None

    def __init__(self):
        self.__parser = HtmlParser()
        self.__parser.addrule('name', r'<span class="nameProduct">(.*?)</span>')
        self.__parser.addrule('desc', r'id="descriptionTab"[^<]*?<p(>.*?<)/p>')
        self.__parser.addrule('br', r'>([^<>"]+)<')
        self.__parser.addrule('img_zoomed', r'<img class="full-gallery-img" src="(.*?)"')
        self.__parser.addrule('img_main', r'other-view-image" src="(.*?)"')

    def __del__(self):
        self.__parser = None

    def find_name(self, src):
        if src is None:
            return None
        name = self.__parser.findall('name', src)
        if len(name) > 0:
            return name[0]
        else:
            return None

    @staticmethod
    def find_price(price_json):
        if price_json is None:
            return None
        try:
            price = json.loads(price_json)
            price = price['price']
        except (KeyError, ValueError, TypeError) as e:
            print('[Error Json KeyError] ' + str(e))
            return None
        if price is None or len(price) < 2:
            return None
        return price[2:len(price)]

    @staticmethod
    def find_currency(price_json):
        if price_json is None:
            return None
        try:
            price = json.loads(price_json)
            price = price['price']
        except (KeyError, ValueError, TypeError) as e:
            print('[Error Json KeyError] ' + str(e))
            return None
        if price is None or len(price) == 0:
            return None
        return price[0:1]

    def findall_desc(self, src):
        if src is None:
            return None
        br = self.__parser.findall('desc', src)
        if len(br) > 0:
            desc = self.__parser.findall('br', br[0])
        else:
            desc = None
        return desc

    def findall_zoomed_images(self, src):
        if src is None:
            return None
        images = self.__parser.findall('img_zoomed', src)
        if len(images) == 0:
            return None
        return images

    def findall_main_images(self, src):
        if src is None:
            return None
        images = self.__parser.findall('img_main', src)
        if len(images) == 0:
            return None
        return images


class ProductUrlParser:
    @staticmethod
    def findall(super_cat_id, data, lang_code):
        js = json.loads(data)
        products = Products()
        try:
            for cat in js['department']:
                for item in cat['products']:
                    try:
                        product = Product(item['id'], item['name_desc_' + lang_code], super_cat_id + '/' + cat['id'] +
                                          '/product/' + item['sku'] + '.html', cat['id'])
                        product.prod_colors = [item['color_group_name']]
                        product.prod_sizes = [item['size']]
                        products.put(product)
                    except KeyError as pe:
                        print('[Error Json KeyError] ' + str(pe))
        except KeyError as e:
            print('[Error Json KeyError] ' + str(e))
        return products


class L1CategoryUrlParser:
    _parser = HtmlParser()

    def __del__(self):
        self._parser = None

    @staticmethod
    def findall(lang, cc):
        cat = Category('e-store', 'e-store', 'http://www.prada.com/' + lang + '/' + cc + '/e-store.html', cstrtime())
        cats = Categories()
        cats.put_cat(cat)
        return cats


class L2CategoryUrlParser(L1CategoryUrlParser):
    def __init__(self):
        self._parser.addrule('titles', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="3" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                       r'/[^<]*?\.html')
        self._parser.addrule('urls', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="3" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                     r'(/[^<]*?\.html)')
        self._parser.addrule('ids', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="3" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                    r'(/[^<]*?)\.html')
        self._parser.addrule('product', r'class="itemPrice"')

    def findall_titles(self, src):
        matches = self._parser.findall('titles', src)
        if len(matches) == 0:
            return None
        titles = [] * 0
        titles.append(matches[0][0])
        for i in range(1, len(matches)):
            found = False
            for title in titles:
                if title == matches[i][0]:
                    found = True
                    break
            if not found:
                titles.append(matches[i][0])
        return titles

    def has_product(self, src):
        matches = self._parser.findall('product', src)
        if len(matches) > 0:
            return True
        else:
            return False

    def findall_urls(self, src):
        matches = self._parser.findall('urls', src)
        if len(matches) == 0:
            return None
        urls = [] * 0
        urls.append(matches[0][len(matches[0]) - 1])
        for i in range(1, len(matches)):
            found = False
            for url in urls:
                if url == matches[i][len(matches[i]) - 1]:
                    found = True
                    break
            if not found:
                urls.append(matches[i][len(matches[i]) - 1])
        return urls

    def findall_ids(self, src):
        matches = self._parser.findall('ids', src)
        if len(matches) == 0:
            return None
        ids = [] * 0
        ids.append(matches[0][len(matches[0]) - 1])
        for i in range(1, len(matches)):
            found = False
            for url in ids:
                if url == matches[i][len(matches[i]) - 1]:
                    found = True
                    break
            if not found:
                ids.append(matches[i][len(matches[i]) - 1])
        return ids


class L3CategoryUrlParser(L2CategoryUrlParser):
    def __init__(self):
        L2CategoryUrlParser.__init__(self)
        self._parser.addrule('titles', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="4" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                       r'/department/[^<]*?\.html')
        self._parser.addrule('urls', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="4" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                     r'/department(/[^<]*?\.html)')
        self._parser.addrule('ids', r'id=[\'"]\w\w\d([^\'"]*)[\'"](( rel="4" )|([^\'"]+))href=[\'"]/.*?/\w\w/e-store'
                                    r'/department(/[^<]*?)\.html')
